package com.mwx.loseweight.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mwx.loseweight.common.utils.BaseContext;
import com.mwx.loseweight.mapper.UserMapper;
//import com.mwx.loseweight.pojo.entity.User;

import com.mwx.loseweight.pojo.entity.User;
import com.mwx.loseweight.pojo.vo.UserLoginVO;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 获取请求中的所有Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 查找名为"userInfo"的Cookie
                if ("userInfo".equals(cookie.getName())) {
                    // 解码Cookie值
                    String encodedUserInfo = cookie.getValue();
                    String userInfoString = URLDecoder.decode(encodedUserInfo, StandardCharsets.UTF_8);
                    // 将字符串转换为UserLoginVO对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    UserLoginVO userLoginVO = objectMapper.readValue(userInfoString, UserLoginVO.class);
                    // 设置用户信息到上下文
                    Long userId = userLoginVO.getId();
                    if (userId == null) {
                        response.setStatus(401);
                        return false;
                    }
                    // 查询数据库是否存在该用户
                    User user = userMapper.selectById(userId);
                    if (user == null) {
                        response.setStatus(401);
                        return false;
                    }
                    BaseContext.setCurrentId(userId);
                    return true;
                }
            }
        }
        response.setStatus(401);
        return false;
    }
}
